package mya.mes.mdc.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import mya.mes.mdc.share.api.MdcModule;
import mya.mes.mdc.share.vo.MdcOptions;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


public class DbManger {
    private static final Object lock = new Object();
    private final Logger logger = LoggerFactory.getLogger(DbManger.class);


    private static final DbManger dbManager = new DbManger();

    private MongoClient mongoClient;
    private MongoDatabase db;

    private boolean insertOrReplace = true;
    private MdcOptions mdcOptions;

    private DbManger() {

    }

    public static DbManger getInstance() {
        if (dbManager.db == null) {
            synchronized (lock) {
                if (dbManager.db == null) {
                    dbManager.connect();
                }
            }
        }

        return dbManager;
    }


    private void connect() {

        if (mdcOptions == null) {
            mdcOptions = MdcModule.getInstance().getMdcOptions();
        }
        String db_url = String.format("mongodb://%s:%d", mdcOptions.MONGO_DB_HOST, mdcOptions.MONGO_DB_PORT);
        mongoClient = MongoClients.create(db_url);
        db = mongoClient.getDatabase(mdcOptions.MONGO_DB_NAME);
    }


    MongoDatabase getDatabase() {
        return db;
    }

    public void shutdown() {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }

}
